import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.regex.Pattern;
public class OfferActions {
	public static void acceptOffer() throws Exception{
		Connection c = mysqlConnection.connect();
		Scanner in = new Scanner(System.in);
		ResultSet addr = null;
		String address;
		Pattern pattern = Pattern.compile("[a-zA-Z]");
		boolean valid = false;
		String i = null;
		//User enters a TradeID;
		do{
			System.out.println("\nWhich offer do you want to accept? (TradeID)");
			i = in.next();
			if(pattern.matches("[a-zA-Z]", i)){
				System.out.println("\nNo characters allowed");
			}
			else{
				valid = true;
			}
		}while(!valid);
		int tradeID = Integer.parseInt(i);
		PreparedStatement p = c.prepareStatement("UPDATE Offers SET Status = 'Accepted', DateCompleted = CURDATE()" +
				"WHERE TradeID = ? AND Status = 'Processing'");
		p.setInt(1, tradeID);
		p.executeUpdate();
		System.out.println("\nTrade Completed");
		PreparedStatement s = c.prepareStatement("SELECT Address FROM Offers,User WHERE UserID = OffererID AND TradeID = ?");
		s.setInt(1, tradeID);
		addr = s.executeQuery();
		while(addr.next()){
			address = addr.getString(1);
			System.out.println("\nSend your item to: ");
			System.out.println(address);
		}
		//Print Out the Offerer's Shipping Address
	}
	public static void declineOffer() throws Exception{
		Connection c = mysqlConnection.connect();
		Scanner in = new Scanner(System.in);
		String j = null;
		boolean valid = false;
		Pattern pattern = Pattern.compile("[a-zA-Z]");
		//User enters a TradeID
		do{
			System.out.println("\nWhich offer do you want to decline? (TradeID)");
			j = in.next();
			if(pattern.matches("[a-zA-Z]", j)){
				System.out.println("\nNo characters allowed");
			}
			else{
				valid = true;
			}
		}while(!valid);
		int tradeID = Integer.parseInt(j);
		PreparedStatement p = c.prepareStatement("UPDATE Offers SET Status = 'Declined', DateCompleted = CURDATE()" +
				"WHERE TradeID = ? AND Status = 'Processing'");
		p.setInt(1, tradeID);
		p.executeUpdate();
		System.out.println("\nTrade Declined");
	}
	public static void viewOffers() throws Exception{
		Connection c = mysqlConnection.connect();
		ResultSet results;
		PreparedStatement ps = c.prepareStatement("SELECT TradeID, OffererID, ItemID, Status FROM Offers WHERE "+
				"ReceiverID = ? AND Status = 'Processing'");
		ps.setInt(1, UserLogin.userID);
		results = ps.executeQuery();
		System.out.println("\nTradeID: " + " " + "OffererID:" + " " + " ItemID:" + " " + " Status:");
		while (results.next()){
			System.out.println(results.getInt(1) + "         " + results.getInt(2) + "           " + results.getInt(3) + "        " + results.getString(4));
		}
	}
	
}

